import React, { useState, useCallback, useMemo } from "react";
import { Input, Dropdown, Button, App } from "antd";
import type { MenuProps } from "antd";
import { useAuth } from "../contexts/AuthContext";
import ThemeModal from "./ThemeModal";

const TopNavbar: React.FC = () => {
  const { logout } = useAuth();
  const [searchValue, setSearchValue] = useState("");
  const [isThemeModalVisible, setIsThemeModalVisible] = useState(false);
  const { message, modal } = App.useApp();

  // 全局搜索处理
  const handleSearch = (value: string) => {
    if (value.trim()) {
      message.info(`搜索: ${value}`);
      // TODO: 实现全局搜索逻辑
      console.log("Global search:", value);
    }
  };

  // 注销登录处理
  const handleLogout = useCallback(() => {
    modal.confirm({
      title: "确认注销",
      content: "您确定要注销登录吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        logout();
        message.success("已成功注销");
      },
    });
  }, [modal, logout, message]);

  // 打开主题模态框
  const handleOpenThemeModal = useCallback(() => {
    setIsThemeModalVisible(true);
  }, []);

  // 关闭主题模态框
  const handleCloseThemeModal = useCallback(() => {
    setIsThemeModalVisible(false);
  }, []);

  // 公告下拉菜单
  const announcementItems: MenuProps["items"] = useMemo(
    () => [
      {
        key: "1",
        label: "系统维护通知",
        icon: <i className="i-mdi-information text-blue-500" />,
      },
      {
        key: "2",
        label: "新功能发布",
        icon: <i className="i-mdi-new-box text-green-500" />,
      },
      {
        key: "3",
        label: "重要更新",
        icon: <i className="i-mdi-alert text-orange-500" />,
      },
      {
        type: "divider",
      },
      {
        key: "all",
        label: "查看全部公告",
        icon: <i className="i-mdi-format-list-bulleted" />,
      },
    ],
    []
  );

  // 客服下拉菜单
  const supportItems: MenuProps["items"] = useMemo(
    () => [
      {
        key: "1",
        label: "在线客服",
        icon: <i className="i-mdi-chat text-blue-500" />,
      },
      {
        key: "2",
        label: "帮助文档",
        icon: <i className="i-mdi-help-circle text-green-500" />,
      },
      {
        key: "3",
        label: "意见反馈",
        icon: <i className="i-mdi-comment-text text-orange-500" />,
      },
      {
        key: "4",
        label: "联系我们",
        icon: <i className="i-mdi-phone text-purple-500" />,
      },
    ],
    []
  );

  const handleAnnouncementClick: MenuProps["onClick"] = useCallback(
    ({ key }: { key: string }) => {
      message.info(`点击了公告: ${key}`);
      // TODO: 实现公告功能
    },
    [message]
  );

  const handleSupportClick: MenuProps["onClick"] = useCallback(
    ({ key }: { key: string }) => {
      message.info(`点击了客服: ${key}`);
      // TODO: 实现客服功能
    },
    [message]
  );

  // 按钮配置数组
  const buttonConfigs = useMemo(
    () => [
      {
        key: "announcement",
        icon: "i-mdi-bullhorn",
        title: "公告",
        hasDropdown: true,
        dropdownItems: announcementItems,
        dropdownHandler: handleAnnouncementClick,
        hasBadge: true,
        onClick: undefined,
        danger: false,
      },
      {
        key: "theme",
        icon: "i-mdi-tshirt-crew",
        title: "换肤",
        hasDropdown: false,
        dropdownItems: undefined,
        dropdownHandler: undefined,
        hasBadge: false,
        onClick: handleOpenThemeModal,
        danger: false,
      },
      {
        key: "support",
        icon: "i-mdi-headset",
        title: "客服",
        hasDropdown: true,
        dropdownItems: supportItems,
        dropdownHandler: handleSupportClick,
        hasBadge: false,
        onClick: undefined,
        danger: false,
      },
      {
        key: "logout",
        icon: "i-mdi-logout",
        title: "注销登录",
        hasDropdown: false,
        dropdownItems: undefined,
        dropdownHandler: undefined,
        hasBadge: false,
        onClick: handleLogout,
        danger: true,
      },
    ],
    [
      announcementItems,
      handleAnnouncementClick,
      supportItems,
      handleSupportClick,
      handleOpenThemeModal,
      handleLogout,
    ]
  );

  // 渲染单个按钮
  const renderButton = useCallback((config: (typeof buttonConfigs)[0]) => {
    const buttonElement = (
      <Button
        type="text"
        size="middle"
        className={`${
          config.hasBadge ? "relative " : ""
        }w-10 h-10 flex items-center justify-center p-0`}
        title={config.title}
        onClick={config.onClick}
        danger={config.danger}
      >
        <i className={`${config.icon} text-lg text-[#333]`} />
        {config.hasBadge && (
          <span className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
        )}
      </Button>
    );

    if (config.hasDropdown) {
      return (
        <Dropdown
          key={config.key}
          menu={{
            items: config.dropdownItems,
            onClick: config.dropdownHandler,
          }}
          placement="bottomRight"
          trigger={["click"]}
        >
          {buttonElement}
        </Dropdown>
      );
    }

    return <div key={config.key}>{buttonElement}</div>;
  }, []);

  return (
    <>
      <div className="h-16 bg-white/80 backdrop-blur-sm border-b border-gray-200/50 px-6 flex items-center justify-between relative z-20">
        {/* 左侧搜索框 */}
        <div className="flex-1 max-w-md">
          <Input
            placeholder="输入关键词搜索"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={(e) =>
              handleSearch((e.target as HTMLInputElement).value)
            }
            size="middle"
            prefix={<i className="i-mdi-magnify text-gray-400" />}
            className="shadow-sm"
            style={{
              backgroundColor: "#eee",
              width: "100%",
            }}
          />
        </div>

        {/* 右侧功能按钮 */}
        <div className="flex items-center space-x-1 ml-6">
          {buttonConfigs.map(renderButton)}
        </div>
      </div>

      {/* 主题切换模态框 */}
      <ThemeModal open={isThemeModalVisible} onClose={handleCloseThemeModal} />
    </>
  );
};

export default TopNavbar;
